import 'dart:convert';
import 'dart:io';

const filename = 'test.txt';
const oldName = 'old.txt';

void fileAsync() async {
  var file = File(filename);
  if (await file.exists()) {
    print("${filename} exists");
  } else {
    print("${filename} isn't exists");
    await file.create();
    print("create ${filename}");
  }

  print('path ${file.path}');
  print('uri ${file.uri}');

  file.writeAsString('hello world');
  var context = await file.readAsString();
  print('context $context');

  var data = await file.readAsBytes();
  print("data ${data}}");

  var lengthSync = await file.length();
  print('length $lengthSync');
}

void fileSync() {
  var file = File(filename);
  if (file.existsSync()) {
    print("${filename} existsSync");
  } else {
    print("${filename} isn't existsSync");
    file.createSync();
    print("createSync ${filename}");
  }
  print('path ${file.path}');
  print('uri ${file.uri}');

  file.writeAsStringSync('hello world');
  var context = file.readAsStringSync();
  print('context $context');

  var lengthSync = file.lengthSync();
  print('length $lengthSync');

  var statSync = file.statSync();
  print('accessed ${statSync.accessed}');
  print('changed ${statSync.changed}');
  print('mode ${statSync.mode}');
  print('size ${statSync.size}');

  file.copySync(oldName);
  // file.renameSync(oldName);
  file.deleteSync();
}

const io_name = 'file.txt';

void io_string() async {
  var file = await File(io_name).create();
  await file.writeAsString('hello dart');
  var content = await file.readAsString();
  print('$content');
  await file.delete();
}

void io_bytes() async {
  var file = await File(io_name).create();
  await file.writeAsBytes(List<int>.from(AsciiCodec().encode('hello world')));
  var content = await file.readAsBytes();
  print('$content');
  var convert = AsciiDecoder().convert(content);
  print('$convert');
  await file.delete();
}

void io_stream() async {
  var file = await File(io_name).create();
  var w = file.openWrite();
  w.write('hello dart');
  await w.close();
  var r = await file.openRead();
  var content = await r.transform(utf8.decoder).first;
  print('$content');
  await file.delete();
}

main() {
  // fileSync();
  // fileAsync();

  // io_string();
  // io_bytes();
  io_stream();
}
